import { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { getApplications, type Application } from '@/lib/api';
import * as LucideIcons from 'lucide-react';
import { Loader2, AlertCircle, ChevronDown, ChevronRight } from 'lucide-react';

/**
 * 图标名称映射到实际的 Lucide 图标组件
 */
function getIconComponent(iconName: string) {
  const IconComponent = (LucideIcons as unknown as Record<string, React.ComponentType<{ className?: string }>>)[iconName];
  return IconComponent || LucideIcons.HelpCircle;
}

/**
 * 动态侧边栏组件
 * 从 API 获取应用列表，动态生成菜单，支持多级菜单
 */
export default function Sidebar() {
  const location = useLocation();
  const [applications, setApplications] = useState<Application[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // 默认展开工作管理、个人备忘、开发工具和AI工具分组
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(
    new Set(['work-management-group', 'personal-memo-group', 'dev-tools-group', 'ai-tools-group', 'agents-group'])
  );

  useEffect(() => {
    async function loadApplications() {
      try {
        setLoading(true);
        setError(null);
        const apps = await getApplications();
        setApplications(apps);
      } catch (err) {
        setError('加载应用列表失败');
        console.error('Failed to load applications:', err);
      } finally {
        setLoading(false);
      }
    }

    loadApplications();
    
    // 监听 storage 事件，当智能体列表变化时重新加载菜单
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'feng-admin-agents') {
        loadApplications();
      }
    };
    
    window.addEventListener('storage', handleStorageChange);
    
    // 自定义事件监听（用于同一窗口内的更新）
    const handleCustomEvent = () => {
      loadApplications();
    };
    
    window.addEventListener('agents-updated', handleCustomEvent);
    
    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('agents-updated', handleCustomEvent);
    };
  }, []);

  const toggleGroup = (groupId: string) => {
    setExpandedGroups((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(groupId)) {
        newSet.delete(groupId);
      } else {
        newSet.add(groupId);
      }
      return newSet;
    });
  };

  // 递归渲染菜单项（支持嵌套分组）
  const renderMenuItem = (app: Application, depth: number = 0) => {
    // 分组菜单
    if (app.type === 'group' && app.children) {
      const Icon = getIconComponent(app.icon);
      const isExpanded = expandedGroups.has(app.id);
      const paddingLeft = depth * 16; // 根据层级增加缩进
      const isTopLevel = depth === 0; // 是否是一级标题
      
      return (
        <div key={app.id} className={depth > 0 ? 'ml-2' : ''}>
          <button
            onClick={() => toggleGroup(app.id)}
            className={cn(
              'flex w-full items-center gap-3 rounded-lg px-3 py-1.5 text-sm transition-colors',
              'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
              isTopLevel && 'font-medium'
            )}
            style={{ paddingLeft: `${paddingLeft + 12}px` }}
          >
            {/* 只有一级标题显示图标 */}
            {isTopLevel && <Icon className="h-5 w-5 flex-shrink-0" />}
            <span className="flex-1 text-left">{app.name}</span>
            {isExpanded ? (
              <ChevronDown className="h-4 w-4 flex-shrink-0" />
            ) : (
              <ChevronRight className="h-4 w-4 flex-shrink-0" />
            )}
          </button>
          
          {isExpanded && (
            <div className={cn(
              'mt-0.5 space-y-0.5',
              isTopLevel ? 'ml-2 border-l-2 border-border pl-1.5' : 'ml-2'
            )}>
              {app.children.map((child) => renderMenuItem(child, depth + 1))}
            </div>
          )}
        </div>
      );
    }
    
    // 普通菜单项
    const isActive = location.pathname === app.path;
    const Icon = getIconComponent(app.icon);
    const paddingLeft = depth * 16;

    return (
      <Link
        key={app.id}
        to={app.path}
        className={cn(
          'flex items-center gap-3 rounded-lg px-3 py-1.5 text-sm transition-colors',
          isActive
            ? 'bg-primary text-primary-foreground'
            : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
        )}
        style={{ paddingLeft: `${paddingLeft + 12}px` }}
      >
        <Icon className="h-5 w-5 flex-shrink-0" />
        <span>{app.name}</span>
      </Link>
    );
  };

  return (
    <aside className="fixed left-0 top-0 z-40 h-screen w-64 border-r bg-background">
      <div className="flex h-full flex-col">
        {/* Logo */}
        <div className="flex h-16 items-center border-b px-6">
          <h1 className="text-xl font-bold">Feng Admin</h1>
        </div>

        {/* Navigation */}
        <nav className="flex-1 space-y-1 overflow-y-auto p-4 sidebar-scrollbar">
          {loading && (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          )}

          {error && (
            <div className="flex flex-col items-center justify-center gap-2 py-8 text-center">
              <AlertCircle className="h-6 w-6 text-destructive" />
              <p className="text-xs text-muted-foreground">{error}</p>
            </div>
          )}

          {!loading && !error && applications
            .filter(app => app.path !== '/app/about' && app.path !== '/app/settings') // 过滤掉关于和设置菜单
            .map((app) => renderMenuItem(app))}
        </nav>

        {/* Bottom Menu - 底部菜单（设置和关于） */}
        {!loading && !error && (() => {
          const settingsApp = applications.find(app => app.path === '/app/settings');
          const aboutApp = applications.find(app => app.path === '/app/about');
          
          if (!settingsApp && !aboutApp) return null;
          
          return (
            <div className="border-t p-4 space-y-0.5">
              {settingsApp && (() => {
                const isActive = location.pathname === settingsApp.path;
                const Icon = getIconComponent(settingsApp.icon);
                
                return (
                  <Link
                    to={settingsApp.path}
                    className={cn(
                      'flex items-center gap-3 rounded-lg px-3 py-1.5 text-sm transition-colors',
                      isActive
                        ? 'bg-primary text-primary-foreground'
                        : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
                    )}
                  >
                    <Icon className="h-5 w-5" />
                    <span>{settingsApp.name}</span>
                  </Link>
                );
              })()}
              
              {aboutApp && (() => {
                const isActive = location.pathname === aboutApp.path;
                const Icon = getIconComponent(aboutApp.icon);
                
                return (
                  <Link
                    to={aboutApp.path}
                    className={cn(
                      'flex items-center gap-3 rounded-lg px-3 py-1.5 text-sm transition-colors',
                      isActive
                        ? 'bg-primary text-primary-foreground'
                        : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
                    )}
                  >
                    <Icon className="h-5 w-5" />
                    <span>{aboutApp.name}</span>
                  </Link>
                );
              })()}
            </div>
          );
        })()}

        {/* Footer */}
        <div className="border-t p-4">
          <div className="rounded-lg bg-muted p-3 text-sm">
            <p className="font-medium">Feng Admin v1.0</p>
            <p className="text-xs text-muted-foreground">动态微应用框架——王剑风开发</p>
          </div>
        </div>
      </div>
    </aside>
  );
}

